const queryUrl = "http://localhost:8080/subject/query"
const selectUrl = "http://localhost:8080/subject/select"
const withdrawUrl = "http://localhost:8080/subject/withdraw"
const identityIdUrl = 'http://localhost:8080/identify/id'

const header = {
    headers: {
        Authorization: localStorage.getItem("Authorization")
    }
};

const queryParams = {
    subjectName: "", // 初始值为空字符串
    showAll: 0, // 初始值为 0
    teacherName: "", // 初始值为空字符串
    orderBy: "id", // 初始排序字段为 "id"
    desc: 0, // 初始值为 0
    page: 1, // 初始页码为 1
    pageSize: 10, // 初始每页大小为 10
    studentId : 0
};

async function getIdentityId() {
    return new Promise((resolve, reject) => {
        const username = localStorage.getItem("LoginUser");
        const url = identityIdUrl + "?username=" + username;
        axios.get(url, header)
            .then((response) => {
                if (response.data.code === 0) {
                    resolve(response.data.data);
                } else {
                    reject(new Error("Error getting identity ID"));
                }
            })
            .catch((err) => {
                reject(err);
            });
    });
}

function updateQueryParams() {
    queryParams.subjectName = document.getElementById("subjectName").value;
    queryParams.showAll = document.getElementById("showAll").checked ? 1 : 0;
    queryParams.teacherName = document.getElementById("teacherName").value;
    queryParams.orderBy = document.getElementById("orderBy").value;
    queryParams.desc = document.getElementById("desc").checked ? 1 : 0;
    queryParams.page = parseInt(document.getElementById("page").value) || 1;
    queryParams.pageSize = parseInt(document.getElementById("pageSize").value) || 10;
    queryParams.studentId = 0

}

function updateMyQueryParams() {
    queryParams.subjectName = document.getElementById("subjectName").value;
    queryParams.showAll = document.getElementById("showAll").checked ? 1 : 0;
    queryParams.teacherName = document.getElementById("teacherName").value;
    queryParams.orderBy = document.getElementById("orderBy").value;
    queryParams.desc = document.getElementById("desc").checked ? 1 : 0;
    queryParams.page = parseInt(document.getElementById("page").value) || 1;
    queryParams.pageSize = parseInt(document.getElementById("pageSize").value) || 10;
    queryParams.studentId = localStorage.getItem("userId");
}

async function selectSubject(id) {
    const studentId = await getIdentityId();
    const url = selectUrl + "?id=" + id + "&studentId=" + studentId;
    axios.post(url,{}, header)
        .then((response) => {
            if(response.data.code === 0) {
                alert("选题成功");
                querySubject();
            } else {
                alert(response.data.msg)
            }
        })
        .catch((err) => {
            alert(err)
        })
}

async function withdrawSubject(id) {
    const studentId = await getIdentityId();
    const url = withdrawUrl + "?id=" + id + "&studentId=" + studentId;
    axios.delete(url, header)
        .then((response) => {
            if(response.data.code === 0) {
                alert("撤销选题成功");
                querySubject();
            } else {
                alert(response.data.msg)
            }
        })
        .catch((err) => {
            alert(err)
        })
}

function queryMySubject() {
    updateMyQueryParams();
    querySubject();
}

function queryAllSubject() {
    updateQueryParams();
    querySubject();
}

function querySubject(){
    const url = `${queryUrl}?${Object.keys(queryParams).map(key => `${key}=${queryParams[key]}`).join('&')}`;
    axios.get(
        url,
        header
    ).then((response)=>{
        if(response.data.code === 0) {
            const subjects = response.data.data; // 假设响应数据是一个包含课题信息的数组
            // 获取用于显示课题的表格
            const subjectTable = document.querySelector("#subjectList table tbody");
            // 清空表格内容，以便显示新的查询结果
            subjectTable.innerHTML = "";
            // 遍历课题数组，并创建课题元素并添加到容器中
            subjects.forEach((subject) => {
                const row = subjectTable.insertRow();
                const idCell = row.insertCell(0);
                const nameCell = row.insertCell(1);
                const difficultyCell = row.insertCell(2);
                const selectedCell = row.insertCell(3);
                const preStudentNameCell = row.insertCell(4);
                const studentNameCell = row.insertCell(5);
                const teacherNameCell = row.insertCell(6);
                const actionCell = row.insertCell(7);

                // 填充单元格内容
                idCell.textContent = subject.id;
                nameCell.textContent = subject.name;
                difficultyCell.textContent = subject.difficulty;
                selectedCell.textContent = subject.selected === 1 ? "是" : "否";
                let preStudentList = "";
                subject.preStudentName.forEach((e) => {
                    preStudentList += " " + e.realName;
                })
                preStudentNameCell.textContent = preStudentList || "N/A";
                studentNameCell.textContent = subject.studentName || "N/A";
                teacherNameCell.textContent = subject.teacherName || "N/A";

                // Add "删除" button for subjects without selected students
                if (subject.selected === 0) {
                    const selectButton = document.createElement("button");
                    const withdrawButton = document.createElement("button");
                    selectButton.classList.add("action-button");
                    withdrawButton.classList.add("action-button");
                    selectButton.textContent = "选择";
                    withdrawButton.textContent = "撤回";
                    selectButton.addEventListener("click", () => selectSubject(subject.id));
                    withdrawButton.addEventListener("click",() => withdrawSubject(subject.id));
                    actionCell.appendChild(selectButton);
                    actionCell.appendChild(withdrawButton);
                } else {
                    actionCell.textContent = "N/A"; // No action needed for selected subjects
                }
            });
        }

    }).catch((err)=>{

    })
}